#pragma once
#include <iostream>
#include <string>
#include <functional>
using namespace std;

class Connection;
class Epoll_server;
using func_c = function<void(Connection *)>;

// 对每一个建立的连接进行描述,并提供一些回调函数处理特定fd
class Connection
{
public:
    Connection(int sockfd, uint32_t events, Epoll_server *epoller = nullptr)
        : _sockfd(sockfd), _events(events), _R(epoller)
    {
    }

    // void SetEpoller(Epoll_server *pe)
    // {
    //     _R = pe;
    // }

    void Fill_callback(func_c recver, func_c sender, func_c excepter)
    {
        _recver = recver;
        _sender = sender;
        _excepter = excepter;
    }

    void AddInBuffer(const string &buffer)
    {
        _inbuffer += buffer;
    }
    void AddOutBuffer(const string &buffer)
    {
        _outbuffer += buffer;
    }

    int Getfd()
    {
        return _sockfd;
    }

    uint32_t Getevents()
    {
        return _events;
    }
    void SetEvents(uint32_t events)
    {
        _events = events;
    }

    string &GetInbuffer()
    {
        return _inbuffer;
    }
    string &GetOutbuffer()
    {
        return _outbuffer;
    }

    bool OutbufferIsempty()
    {
        return _outbuffer.empty();
    }

    void Close()
    {
        close(_sockfd);
    }

    ~Connection()
    {
    }

private:
    int _sockfd;       // 文件描述符
    uint32_t _events;  // 关心的事件
    string _inbuffer;  // 输入缓冲区
    string _outbuffer; // 输出缓冲区

public:
    // 对特定fd处理的回调函数
    func_c _recver;
    func_c _sender;
    func_c _excepter;

    // 专门为listen套接字connection设置的参数
    Epoll_server *_R; // 回指指针(用于在传入回调函数时调用Epoll_server中的方法)
};